/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.orderView.dish;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.table.TableColumn;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TBillDetail;
import com.ruipengkj.bean.TBook;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TExePos;
import com.ruipengkj.bean.TOrder;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.display.ClientDisplay;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.comboBox.JComboBoxDesk;
import com.ruipengkj.component.comboBox.JComboBoxHeight;
import com.ruipengkj.component.jtable.JLabelColorTableCellRenderer;
import com.ruipengkj.component.jtable.JLabelImageTableCellRenderer;
import com.ruipengkj.component.jtable.JPanelCellEditor;
import com.ruipengkj.component.jtable.JPanelTableCellRenderer;
import com.ruipengkj.component.jtable.JTableHeaderImage;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.OrderAddModel;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TBookService;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TExePosService;
import com.ruipengkj.service.TOrderService;
import com.ruipengkj.view.base.BasePanel;
import com.ruipengkj.view.orderView.desk.DeskOrderDialog;

/**
 * 说明： 订单Table,放置菜品
 */
public class OrderTablePanel extends BasePanel {
	private static final long serialVersionUID = 1L;

	private JTable table;//
	private OrderAddModel tableModel;
	private JScrollPane tableJsp;

	private JComboBoxDesk desk;// 桌子下拉框
	private JComboBoxHeight order;// 订单下拉框
	private DefaultComboBoxModel deskModel;// 桌子Model
	private DefaultComboBoxModel orderModel;// 订单Molel

	// table的渲染器、编辑器
	private JPanelCellEditor cellEditor = new JPanelCellEditor();
	// 实施场所service
	private TExePosService tExePosService = BuildSpringApplication
			.getInstance().getTExePosServiceImpl();
	// 订单service
	private TOrderService tOrderService = BuildSpringApplication.getInstance()
			.getTOrderServiceImpl();
	private TCommodityService tCommodityService = BuildSpringApplication
			.getInstance().getTCommodityServiceImpl();
	private TBillDetailService tBillDetailService = BuildSpringApplication
			.getInstance().getTBillDetailServiceImpl();// 单据商品明细
	private TBookService tBookService = BuildSpringApplication.getInstance().getTBookServiceImpl();
	
	private JButton orderButton;//下单按钮
	private boolean bool = true;//

	private int type = 0;//0、点餐界面的 1、餐桌的
	
	public OrderTablePanel() {
		init();
//		queryDesk();
		queryOrder(null);
		Util.setSize(this, 325, 100);
	}
	
	public OrderTablePanel(int type) {
		this.type = type;
		init();
		queryOrder(null);
		Util.setSize(this, 325, 100);
	}

	private void init() {

		tableModel = new OrderAddModel();
		table = uiFactory.createJTable(tableModel, this, 30, JLabel.LEFT);
		table.setShowVerticalLines(false);
		table.setCellSelectionEnabled(false);
		table.setShowHorizontalLines(false);

		table.setRowHeight(36);
		JLabelColorTableCellRenderer JLabelColorTableCellRenderer = new JLabelColorTableCellRenderer(new Color(234, 99, 0));
		table.getColumnModel().getColumn(2)
				.setCellRenderer(new JPanelTableCellRenderer());
		table.getColumnModel().getColumn(2).setCellEditor(cellEditor);
		table.getColumnModel().getColumn(0)
				.setCellRenderer(new JLabelImageTableCellRenderer());
		table.getColumnModel().getColumn(1)
				.setCellRenderer(JLabelColorTableCellRenderer);
//		table.getColumnModel().getColumn(3)
//				.setCellRenderer(JLabelColorTableCellRenderer);
		table.getColumnModel().getColumn(3).setCellRenderer(
						new JLabelColorTableCellRenderer(new Color(80, 179, 1)));
		table.setBackground(Color.white);
		table.getTableHeader().setDefaultRenderer(new JTableHeaderImage());
		tableJsp = new JScrollPane(table) {
			private static final long serialVersionUID = 1L;

			@Override
			public void paintBorder(Graphics g) {
				g.setColor(new Color(234, 99, 0));
				g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
			}
		};
		tableJsp.setOpaque(false);
		tableJsp.getViewport().setOpaque(false);
		tableJsp.setBackground(Color.white);

		this.setBackground(Color.white);
		this.setLayout(new BorderLayout());
		this.add(tableJsp);
		this.add(initTop(), BorderLayout.NORTH);
		this.add(uiFactory.createFlowJPanel(), BorderLayout.WEST);
	}

	// 添加table一行
	public void addTableRow(TCommodity commodity) {
		JButton jb1 = createJButto("+", 42, 25,
				ImageFactory.loadImage(ImageFactory.BTN_TABLE_ADD), true, null);
		JButton jb2 = createJButto("-", 42, 25,
				ImageFactory.loadImage(ImageFactory.BTN_TABLE_SUB), true, null);
		JTextField tf = new JTextField(2);

		JPanel jp = new JPanel(new FlowLayout(FlowLayout.LEFT)) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void paintBorder(Graphics g) {
				g.setColor(new Color(175, 173, 173));
				int x = 0;
				int y = this.getHeight() - 1;
				while (x <= this.getWidth() - 1) {
					g.drawLine(x, y, x, y);
					x += 2;
				}
			}
		};
		jp.add(jb1);
		jp.add(tf);
		jp.add(jb2);
		jp.setOpaque(false);

		tf.setEditable(false);
		if (commodity != null && commodity.getNum() != 0) {
			tf.setText(commodity.getNum() + "");
		} else {
			tf.setText("1");
		}

		commodity.setPanel(jp);
		tableModel.addList(commodity);
		// table.updateUI();

		setTableColumnWidth();
		TabelUtil.setTableColumnWidths(table, 0, 160);
		TabelUtil.setTableColumnWidths(table, 2, 120);
		TabelUtil.setTableColumnWidths(table, 3, 60);
	}

	private JButton createJButto(String text, int width, int height,
			ImageIcon icon, boolean isEnabled, Border border) {
		JButton jb = new JButton();// text显示文本
		jb.setIcon(icon);
		jb.addActionListener(this);// 添加监听器
		jb.setEnabled(isEnabled);// 是否可编辑
		jb.setBorder(border);
		jb.setFocusPainted(false);
		jb.setBorderPainted(false);
		jb.setContentAreaFilled(false);
		return jb;
	}

	private JPanel initTop() {
		JPanel jp = uiFactory.createFlowJPanel(FlowLayout.CENTER, 0, 0);

		deskModel = new DefaultComboBoxModel();
		desk = new JComboBoxDesk(deskModel);
		Util.setSize(desk, 124, 30);
		desk.addActionListener(this);
		
		orderButton = new RPJButtonWhite("点  菜");
		orderButton.addActionListener(this);
		if (type != 1) {
			jp.add(desk);
		} else {
			jp.add(orderButton);
			jp.add(uiFactory.createJLabel("  "));
		}
		orderModel = new DefaultComboBoxModel();
		order = new JComboBoxHeight(orderModel);
		Util.setSize(order, 180, 30);
		jp.add(order);
		order.addActionListener(this);

		return jp;
	}

	public void queryDesk() {
		deskModel.removeAllElements();
		deskModel.addElement(new JComboBoxPOJO("没有餐桌"));
//		try {
//			deskModel.removeAllElements();
//			deskModel.addElement(new JComboBoxPOJO("无餐桌"));
//			List<TExePos> tExePosList = tExePosService.findService(null);
//			if (tExePosList != null && tExePosList.size() != 0) {
//				for (int i = tExePosList.size() - 1; i >= 0; --i) {
//					TExePos tExePos = tExePosList.get(i);
//					deskModel.addElement(new JComboBoxPOJO(tExePos.getPosID(),
//							tExePos.getName(), tExePos));
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}

	public void queryOrder(TExePos tExePos) {
		try {
			orderModel.removeAllElements();
			orderModel.addElement(new JComboBoxPOJO("新单"));
			TOrder tOrder = new TOrder();
			String posID = null;
			if (tExePos  == null) {
				JComboBoxPOJO po = (JComboBoxPOJO) desk.getSelectedItem();
				if (po != null) 
					posID = po.getIdStr();
			} else {
				posID = tExePos.getPosID();
			}
			// 条件：消费实施场所
			tOrder.setPosID(posID);
			// 条件：未支付的
			tOrder.setPayStatus(ApplicationContext.PLAY_STATUS_NO);
			
			//查询订单信息
			List<TOrder> tOrderList = tOrderService.findByDeskService(tOrder);
			
			if (tOrderList != null && tOrderList.size() != 0) {
				for (int i = tOrderList.size() - 1; i >= 0; --i) {
					tOrder = tOrderList.get(i);
					orderModel.addElement(new JComboBoxPOJO(tOrder.getPosID(),
							"订单" + (i + 1), tOrder));
				}
				//有订单   桌子处于使用状态
				setDeskStatus(tExePos, ApplicationContext.DESK_STATUS2);
			} else {
				setDeskStatus(tExePos, ApplicationContext.DESK_STATUS1);
			}
			
			TBook tBook = new TBook();
			tBook.setPosID(posID);
			tBook.setShow(true);
			//查询预订信息
			List<TBook> tBookList = tBookService.findService(tBook);
			if (tBookList!= null && tBookList.size() != 0) {
				for (int i = tBookList.size() - 1; i >= 0; --i) {
					tBook = tBookList.get(i);
					orderModel.addElement(new JComboBoxPOJO(tBook.getPosID(),
							"预订单" + (i + 1), tBook));
				}
				if (tOrderList == null || tOrderList.size()==0)//不存在订单，存在预订信息时
					setDeskStatus(tExePos, ApplicationContext.DESK_STATUS3);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**返回新单处*/
	public void newOrder() {
		order.setSelectedIndex(0);
	}
	
	TBillDetailService tBillDetailServic = BuildSpringApplication.getInstance().getTBillDetailServiceImpl();
	/**删除当前选中订单*/
	public void delOrder() {
		TOrder order = getOrder();
		TBillDetail tBillDetail = new TBillDetail();
		tBillDetail.setBillID(order.getOrderID());
		try {
			List<TBillDetail> tBillDetailList = tBillDetailServic.findService(tBillDetail);
			for (int i = tBillDetailList.size()-1; i >= 0; --i) {
				tBillDetailServic.deleteService(tBillDetailList.get(i).getDetailID());
			}
			tOrderService.deleteService(order.getOrderID());
			
			this.order.removeItem(this.order.getSelectedItem());
			this.order.updateUI();
			
			queryOrder(this.getTExePos());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	// 清空所有数据
	private void cleanData(boolean isDelete) {
		if (isDelete) {// 删除所有数据
			tableModel.getTCommodityList().clear();
			tableModel.fireTableRowsDeleted(0, table.getRowCount());
		} else {// 不删除数据，重新new
			tableModel.setRowData(new ArrayList<TCommodity>());
			tableModel.fireTableRowsDeleted(0, table.getRowCount());
		}
	}

	public List<TCommodity> getTCommodityList() {
		return tableModel.getTCommodityList();
	}

	public void setTCommodityList(List<TCommodity> tCommodityList) {
		this.tableModel.setRowData(tCommodityList);
		table.updateUI();
		// TabelUtil.setJTabelAutoClumnWidth(table);
		TabelUtil.setTableColumnWidths(table, 2, 120);
	}

	/** 查单 */
	public void orderAction() {
		try {
			cleanData(true);
			clear();//清空信息，例如：原本的价格，数量，会员信息等
			TOrder tOrder = getOrder();
			if (tOrder == null)
				return;
			
			TBillDetail tBillDetail = new TBillDetail(ApplicationContext.BILL_BILLTYPE3, tOrder.getOrderID());
			List<TBillDetail> tBillDetailList = tBillDetailService.findCommodityIDService(tBillDetail);
			if (tBillDetailList != null && tBillDetailList.size() != 0) {
				for (int i = tBillDetailList.size() - 1; i >= 0; --i) {
					TCommodity tCommodity = tCommodityService
							.getByIdService(tBillDetailList.get(i)
									.getCommodityID());
					tCommodity.setNum(tBillDetailList.get(i).getNum());
					addTableRow(tCommodity);
					TotalPrice(tCommodity, tBillDetailList.get(i).getNum());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == desk) {
			queryOrder(null);
		} else if (e.getSource() == order) {
			orderAction();
		}  else if (e.getSource() == orderButton) {
			new DeskOrderDialog() {
				private static final long serialVersionUID = 1L;
				protected void addDish(TCommodity tCommodity) {
					List<TCommodity> tCommodityList = getTCommodityList();
					try {// 客显，+商品金额
						ClientDisplay.sendDisplay(
								ClientDisplay.DISPLAY_STATE_PRICE,
								tCommodity.getDiscountPrice() + "");
					} catch (Exception e) {
						e.printStackTrace();
					}
					for (int i = tCommodityList.size() - 1; i >= 0; --i) {
						if (tCommodity.getCommodityID().equals(
								tCommodityList.get(i).getCommodityID())) {
							clickAddButton(i);
							return;
						}
					}
					tCommodity.setNum(1);
					addTableRow(tCommodity);
					if (tCommodity != null) {
						TotalPrice(tCommodity, 1);
					}
				};
			}.show(this, -760, 0);
		} else {
			List<TCommodity> tCommodityList = tableModel.getTCommodityList();
			for (int i = tCommodityList.size() - 1; i >= 0; --i) {
				// 点击了table中面板中的按钮
				JPanel jp = tCommodityList.get(i).getPanel();

				// 第二个组件，JTextField
				JTextField tf = (JTextField) jp.getComponent(1);
				String value = tf.getText();
				if (e.getSource() == jp.getComponent(0)) {
					// 点击了第一个组件（即点击了+按钮时）
					tf.setText(Integer.parseInt(value) + 1 + "");
					table.setValueAt(tf.getText(), i, 2);
					if (!jp.getComponent(2).isEnabled()) {
						jp.getComponent(2).setEnabled(true);
						((JButton) jp.getComponent(2)).setIcon(ImageFactory
								.loadImage(ImageFactory.BTN_TABLE_SUB));
					}
					TotalPrice(i, 1);
					jp.requestFocus();
					tf.requestFocus();
					jp.updateUI();
					return;
				} else if (e.getSource() == jp.getComponent(2)) {
					// 点击了第3个组件（即点击了-按钮时）
					tf.setText(Integer.parseInt(value) - 1 + "");
					TotalPrice(i, -1);
					if (tf.getText().equals("0")) {
						tableModel.getTCommodityList().remove(i);
						setTableColumnWidth();
						this.updateUI();
					} else {
						table.setValueAt(tf.getText(), i, 2);
					}
					return;
				}
			}
		}
	}

	public void clickAddButton(int i) {
		((JButton) tableModel.getTCommodityList().get(i).getPanel()
				.getComponent(0)).doClick();
		setTableColumnWidth();
	}

	// 设置table的行宽度，使table重画，使商品的数量正确
	private void setTableColumnWidth() {
		TableColumn tableColumn = table.getColumnModel().getColumn(2);
		tableColumn.setPreferredWidth(tableColumn.getPreferredWidth()
				+ (bool ? -1 : 1));
		bool = !bool;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == table && table.getSelectedColumn() != 2) {
			TCommodity selectCommodity = tableModel.getTCommodityList().get(
					table.getSelectedRow());
			OrderDishCookingDialog OrderDishCookingDialog = new OrderDishCookingDialog();
			OrderDishCookingDialog.showDialog(selectCommodity.getCooking());
			if (OrderDishCookingDialog.isSuccess) {
				selectCommodity.setCooking(OrderDishCookingDialog.getText());
			}
		}
	}

	public TOrder getOrder() {
		JComboBoxPOJO po = (JComboBoxPOJO) order.getSelectedItem();
		if (po != null) {
			if (po.getObject() instanceof TOrder)
				System.out.println(po.getObject());
				return (TOrder) po.getObject();
		}
		return null;
	}
	
	public String getPosID() {
		JComboBoxPOJO po = (JComboBoxPOJO) desk.getSelectedItem();
		if (po != null) {
			return po.getIdStr();
		}
		return null;
	}
	
	public TExePos getTExePos() {
		JComboBoxPOJO po = (JComboBoxPOJO) desk.getSelectedItem();
		if (po != null && po.getIdStr() != null) {
			return (TExePos)po.getObject();
		} else {
			return null;
		}
	}

	private void setDeskStatus(TExePos tExePos, byte status) {
		if (tExePos == null) {
			JComboBoxPOJO po = (JComboBoxPOJO) desk.getSelectedItem();
			if (po != null && po.getObject() != null) {
				tExePos = (TExePos)po.getObject();
			}
		}
		
		if (tExePos != null && tExePos.getPosID() != null && !tExePos.getPosID().equals("")) {
			tExePos.setStatus(status);
			try {
				tExePosService.saveOrUpdateService(tExePos);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public JComboBox getDesk() {
		return desk;
	}

	// 统计价格
	protected void TotalPrice(int num, int addOrSub) {
	}
	protected void TotalPrice(TCommodity num, int addOrSub) {
	}

	@Override
	public void clear() {
		
	}
}
